package com.swallow.auth.infrastructure.impl.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.swallow.auth.domain.auth.model.AccountEntity;
import com.swallow.auth.domain.auth.repository.repository.IAuthDomainRepository;
import com.swallow.auth.infrastructure.convert.auth.CvtAuthRepoMapper;
import com.swallow.auth.infrastructure.mysql.mapper.AccountMapper;
import com.swallow.auth.infrastructure.mysql.po.AccountPO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: yangjie.deng@resico.cn
 * @since: 2024-05-13 11:48:06
 * @version: v1.0.0
 * @describe:
 */
@Slf4j
@Service
public class AuthDomainRepositoryImpl implements IAuthDomainRepository {
    @Resource
    AccountMapper accountMapper;

    @Override
    public Map<String, Boolean> dupCheck(AccountEntity accountEntity) {
        LambdaQueryWrapper<AccountPO> wrappers = Wrappers.lambdaQuery(AccountPO.class)
                                                         .eq(AccountPO::getDeleteFlag, 0)
                                                         .and(wrapper -> wrapper.eq(AccountPO::getMobile, accountEntity.getMobile())
                                                                                .or()
                                                                                .eq(AccountPO::getAccountName, accountEntity.getUsername()));


        List<AccountPO> list = accountMapper.selectList(wrappers);

        if (CollectionUtils.isEmpty(list)) {
            return Map.of();
        }
        Map<String, Boolean> valueMap = new HashMap<>();
        list.forEach(item -> {
                        if (StringUtils.equals(item.getAccountName(), accountEntity.getUsername())) {
                            valueMap.put("用户名", Boolean.TRUE);
                        }
                        if (StringUtils.equals(item.getMobile(), accountEntity.getMobile())) {
                            valueMap.put("手机号", Boolean.TRUE);
                        }
                    });
        return valueMap;
    }


    @Override
    public void accountCreate(AccountEntity entity) {
        AccountPO accountPO = CvtAuthRepoMapper.INSTANCE.accountEntity2PO(entity);
        accountMapper.insert(accountPO);
    }

    @Resource private PasswordEncoder passwordEncoder;

    @Override
    public String encryptPwd(String password) {
        return passwordEncoder.encode(password);
    }
}
